package xc.doughnut.service;

import lombok.extern.slf4j.Slf4j;
import xc.doughnut.util.OracleGenerator;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: OracleService
 * @package: xc.doughnut.service
 * @author: XuChao
 * @description: Oracle对数据库的操作
 * @date: 2023/4/6 9:52
 */
@Slf4j
public class IOracleService {

    // URL
    public static final String URL = OracleGenerator.DATA_SOURCE_URL;
    // 数据库用户名
    public static final String USERNAME = OracleGenerator.DATA_SOURCE_USER_NAME;
    // 数据库密码
    public static final String PASSWORD = OracleGenerator.DATA_SOURCE_PASSWORD;

    /**
     * 获取Connection连接
     */
    public Connection getConnection() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            log.info("获取连接:" + connection);
            return connection;
        }catch (Exception e){
            e.printStackTrace();
            log.error("获取连接失败:" + e.getMessage());
            return null;
        }
    }

    /**
     * 查询获取数据库所有表名,返回String[]
     */
    public String[] findAllTablesArr(){
        return this.findAllTables().stream().toArray(String[]::new);
    }

    /**
     * 查询获取数据库所有表名,返回List集合
     */
    public List<String> findAllTables(){
        Connection connection = this.getConnection();
        ResultSet rs = null;
        try {
            List<String> tables = new ArrayList<>();
            //获取数据库的元数据
            DatabaseMetaData db = connection.getMetaData();
            //从元数据中获取到所有的表名
            rs = db.getTables(null, IOracleService.USERNAME, null,
                                        new String[] { "TABLE" }
            );
            while(rs.next()) {
                tables.add(rs.getString(3));
            }
            return tables;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            this.closeConnection(connection);
        }
    }

    /**
     * 关闭数据库连接
     */
    public void closeConnection(Connection connection) {
        if(connection != null) {
            try {
                connection.close();
                log.info("连接关闭:" + connection);
            } catch (SQLException e) {
                e.printStackTrace();
                log.error("关闭连接失败:" + e.getMessage());
            }
        }
    }

}
